package com.aiguigu.test;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class bishi {
    public static void main(String[] args) {
        PC pc = new PC();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i <34 ; i++) {
                    pc.print1();
                }
            }
        },"线程一").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i <33 ; i++) {
                    pc.print2();
                }
            }
        },"线程二").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i <33 ; i++) {
                    pc.print3();
                }
            }
        },"线程三").start();

    }
    static class PC{
        private Integer number = 1;
        private Integer temp=1;
        private Lock lock = new ReentrantLock();
        private Condition c1 = lock.newCondition();
        private Condition c2 = lock.newCondition();
        private Condition c3 = lock.newCondition();

        public void print1(){
            lock.lock();
            try {
                while (temp != 1){
                    c1.await();
                }
                System.out.println(Thread.currentThread().getName()+number);
                number ++;
                temp = 2;
                c2.signal();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }

        public void print2(){
            lock.lock();
            try {
                while (temp!= 2){
                    c2.await();
                }
                System.out.println(Thread.currentThread().getName()+number);
                number ++;
                temp = 3;
                c3.signal();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }

        public void print3(){
            lock.lock();
            try {
                while (temp!= 3){
                    c3.await();
                }
                System.out.println(Thread.currentThread().getName()+number);
                number ++;
                temp=1;
                c1.signal();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }

    }

}
